package jinyilw.swing.visuals.panel;

import jinyilw.common.Operator;
import jinyilw.swing.ColorTools;

import javax.swing.JComponent;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;

public class ImagePanel extends JComponent // 图像面板
{
	private static final long serialVersionUID = 1005671082158481413L;
	protected Image image;
	private int opacity = 0;

	public ImagePanel()
	{
	}

	public ImagePanel(Image img)
	{
		image = img;
	}

	public void setImage(Image img)
	{
		if (image != img)
		{
			image = img;
			if (isShowing())
				repaint();
		}
	}

	public void setColor(Color color)
	{
		setOpaque(true);
		setBackground(color);
		image = null;
	}

	public Image getImage()
	{
		return image;
	}

	public void setOpacity(int opacity)
	{
		this.opacity = opacity;
	}

	public void addClickOperator(final Operator<MouseEvent> operator)
	{
		this.addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent e)
			{
				if (e.getClickCount() == 1)
					operator.operate(e);
			}
		});
	}

	public void addDoubleClickOperator(final Operator<MouseEvent> operator)
	{
		this.addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent e)
			{
				if (e.getClickCount() == 2)
					operator.operate(e);
			}
		});
	}

	@Override
	protected void paintComponent(Graphics g)
	{
		if (image != null)
			g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
		if (opacity > 0 && opacity <= 255)
		{
			g.setColor(ColorTools.getAlphaColor(getBackground(), opacity));
			g.fillRect(0, 0, getWidth(), getHeight());
		}
	}

	public void setImageArea(int x, int y, int w, int h)
	{
		if (image != null)
		{
			image = ((BufferedImage) image).getSubimage(x, y, w, h);
			if (isShowing())
				repaint();
		}
	}

	public void clearImage()
	{
		image = null;
		if (isShowing())
			repaint();
	}
}
